 //
//  EnjoyViewController.m
//  FreeReading
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 lanou3g. All rights reserved.
//

#import "EnjoyViewController.h"
#import <CoreLocation/CoreLocation.h>
#import "HeaderCell.h"
#import "EnjoyCell.h"
#import "AllPicCell.h"
#import "EnjoyModel.h"
#import "ImageButton.h"
#import "ImageButtonView.h"
#import "EnjoyDetailViewController.h"
#import "CategoryViewController.h"
#import "MoreTableViewController.h"
#import "CityListVC.h"

@interface EnjoyViewController () <CLLocationManagerDelegate>

// 数据存放容器
@property (nonatomic, strong) NSMutableArray *dataArray;
// 城市显示Label
@property (nonatomic, strong) UILabel *cityLabel;

@property (nonatomic, strong) CLLocationManager *locationManager;

@end

@implementation EnjoyViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [[NSUserDefaults standardUserDefaults] setObject:kDay forKey:KEK];
    [[NSUserDefaults standardUserDefaults] synchronize];
    if ([EnjoyDataManager shareManager].cityName == nil || [EnjoyDataManager shareManager].cityCode == nil) {
        
        [HUDHeaper addHUDInView:self.view text:@"正在定位"];
        [self getLocation];
        
    }
    // 取消内边距
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 7.0) {
        
        self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    // 注册cell
    [self.tableView registerNib:[UINib nibWithNibName:@"EnjoyCell" bundle:nil] forCellReuseIdentifier:@"EnjoyCell"];
    [self.tableView registerNib:[UINib nibWithNibName:@"AllPicCell" bundle:nil] forCellReuseIdentifier:@"AllPicCell"];
    [self setSubViews];
    [self.tableView addLegendHeaderWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
}
// 获取位置信息
- (void)getLocation
{
    self.locationManager = [[CLLocationManager alloc] init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestAlwaysAuthorization];
    
    if ([CLLocationManager locationServicesEnabled]) {
        
        [self.locationManager startUpdatingLocation];
    } else {
        if ([EnjoyDataManager shareManager].cityCode == nil) {
            
                    self.cityLabel.text = @"定位失败";
                    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"定位失败请选择城市" preferredStyle:(UIAlertControllerStyleAlert)];
                    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            
                        CityListVC *cityListVC = [[CityListVC alloc] init];
            
                        [self.navigationController pushViewController:cityListVC animated:YES];
            
                    }];
                    [alert addAction:action];
                    [self presentViewController:alert animated:YES completion:nil];
            
        }

    }
}
// 下拉刷新

- (void)loadNewData
{
    [self loadData];
}

#pragma mark - 处理数据
- (void)loadData
{
    
    // 判断网络状态
    AFNetworkReachabilityManager *net_manager = [AFNetworkReachabilityManager sharedManager];
    [net_manager startMonitoring];
    [net_manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == AFNetworkReachabilityStatusUnknown || status == AFNetworkReachabilityStatusNotReachable) {
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"网络异常 请检查网络后再试" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
                return ;
                
            }];
            
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
        }
        
        
    }];
    
    self.cityLabel.text = [EnjoyDataManager shareManager].cityName;
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/html",@"text/json",@"text/javascript", nil];
    
    NSString *urlString = [NSString stringWithFormat:kEnjoyUrl, [EnjoyDataManager shareManager].cityCode];
    
    [manager GET:urlString parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
        // 是否显示类目
        NSString *isShowCategory = responseObject[@"data"][@"info"][@"show_category"];
        [EnjoyDataManager shareManager].showCategory = isShowCategory;
        // 根据isShowCategory判断是否显示TableViewHeader
        if ([isShowCategory isEqualToString:@"Y"]) {
            [self addTableViewHeader];
        } else {
            
            // 去掉表头
            self.tableView.tableHeaderView = nil;
        }
        
        // 解析数据
        NSArray *dataArray = responseObject[@"data"][@"columns"];
        NSMutableArray *tempArray = [NSMutableArray array];
        for (NSDictionary *dic in dataArray) {
            
            NSMutableArray *tempDataArray = [NSMutableArray array];

            NSString *sectionImageUrl = dic[@"banner"][@"url"];
            
            for (NSDictionary *dict in dic[@"items"]) {
                EnjoyModel *model = [[EnjoyModel alloc] init];
                [model setValuesForKeysWithDictionary:dict];
                model.more_type = dic[@"more_type"];
                [tempDataArray addObject:model];
            }
            
          NSDictionary *tempDic = @{@"models":tempDataArray, @"url":sectionImageUrl, @"show_more":dic[@"show_more"]};
            [tempArray addObject:tempDic];
        }
        self.dataArray = tempArray;
        [HUDHeaper hideAllHUDsForView:self.view animated:YES];
        [self.tableView.header endRefreshing];
        // 刷新tableView
        [self.tableView reloadData];
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
        
        NSString *message = [NSString stringWithFormat:@"%@", [error localizedDescription]];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            return ;
        }];
        
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];

        
    }];
}

#pragma mark - 添加tableView header
- (void)addTableViewHeader
{
    ImageButtonView *buttonView = [[ImageButtonView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 80)];
    // 添加点击方法
    for (UIView *view in buttonView.subviews) {
        if ([view isKindOfClass:[ImageButton class]]) {
            
        ImageButton *button = (ImageButton *)view;
        [button addTarget:self action:@selector(didSelectButton:) forControlEvents:UIControlEventTouchUpInside];
        }
    }
    
    if ([[[NSUserDefaults standardUserDefaults] objectForKey:KEK] isEqualToString:kNight]) {
        
        for (UIView *view in buttonView.subviews) {
            if ([view isKindOfClass:[UILabel class]]) {
                UILabel *label = (UILabel *)view;
                label.textColor = [UIColor grayColor];
            }
        }
        
    }
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(kMargin / 2, buttonView.height - 0.5, kScreenWidth - kMargin, 0.5)];
    lineView.backgroundColor = [UIColor grayColor];
    [buttonView addSubview:lineView];
    self.tableView.tableHeaderView = buttonView;
}
#pragma mark - 设置子视图
- (void)setSubViews
{
    
    // 取消滚动条
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    // 标题显示
    UILabel *titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 100, 30)];
    titleLabel.tag = 100;
    titleLabel.textColor = [UIColor whiteColor];
    titleLabel.text = @"玩乐";
    titleLabel.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLabel;
   
    // 设置导航条的颜色及item的颜色
      [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBar"] forBarMetrics:(UIBarMetricsDefault)];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    
    // 添加UIBarButtonItem
    UIBarButtonItem *rightButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"iconfont-shaixuan-1"] style:(UIBarButtonItemStylePlain) target:self action:@selector(filtCities:)];
    self.navigationItem.rightBarButtonItem = rightButton;
}
#pragma mark - 是否显示城市
-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    // 隐藏tabBar
    self.hidesBottomBarWhenPushed = YES;
    [HUDHeaper addHUDProgressInView:self.view text:@"加载中..."];
    [self loadData];
    [self showCityName];
}

-(void)viewWillDisappear:(BOOL)animated
{

    [super viewWillDisappear:animated];
    self.hidesBottomBarWhenPushed = NO;
    [self.cityLabel removeFromSuperview];
}
// 显示城市
- (void)showCityName
{
    // 显示城市
    self.cityLabel = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth - 90, kMargin / 2, 50, 20)];
    self.cityLabel.textColor = [UIColor whiteColor];
    self.cityLabel.textAlignment = NSTextAlignmentRight;
    self.cityLabel.font = [UIFont systemFontOfSize:12];
    self.cityLabel.text = [EnjoyDataManager shareManager].cityName;
    [self.navigationController.navigationBar addSubview:self.cityLabel];
}
#pragma mark - 筛选按钮
- (void)filtCities:(UIBarButtonItem *)rightButton
{

    CategoryViewController *categoryVC = [[CategoryViewController alloc] init];
    [self.navigationController pushViewController:categoryVC animated:YES];
    
}
#pragma mark - 点击button触发的方法
- (void)didSelectButton:(ImageButton *)button
{
    MoreTableViewController *moreVC = [[MoreTableViewController alloc] init];
    UINavigationController *naVC = [[UINavigationController alloc] initWithRootViewController:moreVC];
    naVC.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
    
    switch (button.index) {
        case 0:
        {
            moreVC.url = [NSString stringWithFormat:kArtUrl, 1, [EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"演艺";
            break;
        }
        case 1:
        {
             moreVC.url = [NSString stringWithFormat:kArtUrl, 4, [EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"度假";

            break;
        }
        case 2:
        {
             moreVC.url = [NSString stringWithFormat:kMovieUrl,[EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"电影";
            break;
        }
        case 3:
        {
             moreVC.url = [NSString stringWithFormat:kArtUrl, 9, [EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"美食";

            break;
        }
        case 4:
        {
             moreVC.url = [NSString stringWithFormat:kArtUrl, 3, [EnjoyDataManager shareManager].cityCode];
            moreVC.titles = @"活动";
            
            break;
        }
        default:
            break;
    }
    [self presentViewController:naVC animated:YES completion:nil];
}

#pragma mark - 内存警告
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if ([self isViewLoaded] && self.view.window == nil) {
        
        self.view = nil;
    }
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   
    return self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    NSDictionary *dic = self.dataArray[section];
    NSArray *dataArray = dic[@"models"];
    return dataArray.count + 1;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (!self.dataArray.count > 0) {
    
        return nil;
        
    } else {
   
    NSDictionary *dic = self.dataArray[indexPath.section];
    
    if (indexPath.row == 0) {

    static NSString *identifier = @"HeaderCell";
    HeaderCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        
        cell = [[HeaderCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
        [cell loadHeaderImageWith:dic[@"url"] isShowMore:dic[@"show_more"]];
    return cell;
        
    } else {
        
        EnjoyModel *model = dic[@"models"][indexPath.row - 1];
        if ([model.tpl_cell_style isEqualToString:@"all_pic"]) {
            
       AllPicCell *cell = [tableView dequeueReusableCellWithIdentifier:@"AllPicCell" forIndexPath:indexPath];
            cell.model = model;
        return cell;
        } else {
            
        EnjoyCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EnjoyCell" forIndexPath:indexPath];
            cell.model = model;
        return cell;
        
        }
    }
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];

    if (indexPath.row == 0) {
        return 80;
    } else {
        EnjoyModel *model = dic[@"models"][indexPath.row - 1];

        if ([model.tpl_cell_style isEqualToString:@"all_pic"]) {
            return 200;
        } else {
            
    return 280;
            
        }
    }
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 0;
}
#pragma mark - cell点击方法
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary *dic = self.dataArray[indexPath.section];
    if (indexPath.row == 0) {
        
        // 分区头cell
        
        
    } else {
        EnjoyModel *model = dic[@"models"][indexPath.row - 1];
        
    EnjoyDetailViewController *detailVC = [[EnjoyDetailViewController alloc] init];
        detailVC.url = model.detailUrl;
        detailVC.newsTitle = model.title;
        detailVC.pic_url = model.picUrl;
        detailVC.tag = @"1";
        [self.navigationController pushViewController:detailVC animated:YES];
        
    }
}

#pragma mark - CLLocationManagerDelegate
// 定位成功
-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations
{
    
    NSString *url = [NSString stringWithFormat:kCityListUrl_02, locations.firstObject.coordinate.latitude, locations.firstObject.coordinate.longitude];
    AFHTTPRequestOperationManager *manager_ =[AFHTTPRequestOperationManager manager];
    [manager_ GET:url parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        
       NSDictionary *dic = responseObject[@"data"][@"lbs_city"];
        
        if (dic[@"city_code"] == nil) {
            
            self.cityLabel.text = @"定位失败";
            
            UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"定位失败请选择城市" preferredStyle:(UIAlertControllerStyleAlert)];
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
              
                CityListVC *cityListVC = [[CityListVC alloc] init];
                
                [self.navigationController pushViewController:cityListVC animated:YES];
              
            }];
            [alert addAction:action];
            [self presentViewController:alert animated:YES completion:nil];
            return;

        }

        [HUDHeaper addHUDInView:self.view text:[NSString stringWithFormat:@"%@%@", @"当前城市:", dic[@"city_name"] ]hideAfterDelay:5.0];
        [EnjoyDataManager shareManager].cityCode = dic[@"city_code"];
        [EnjoyDataManager shareManager].cityName = dic[@"city_name"];
        
       
        [self loadData];
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        
        
        NSString *message = [NSString stringWithFormat:@"%@", [error localizedDescription]];
        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:message preferredStyle:(UIAlertControllerStyleAlert)];
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
            return ;
        }];
        
        [alert addAction:action];
        [self presentViewController:alert animated:YES completion:nil];

    }];
}
// 定位失败
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
      self.cityLabel.text = @"定位失败";
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:@"定位失败请选择城市" preferredStyle:(UIAlertControllerStyleAlert)];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        
        CityListVC *cityListVC = [[CityListVC alloc] init];
        
        [self.navigationController pushViewController:cityListVC animated:YES];
    }];
    [alert addAction:action];
    [self presentViewController:alert animated:YES completion:nil];

}
#pragma mark - 懒加载方法
-(NSMutableArray *)dataArray
{
    if (_dataArray == nil) {
        
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}

@end
